import React, {Component} from 'react';
import {
  View,
  Text,
  StyleSheet,
  ScrollView,
  ToastAndroid,
  Image,
  TouchableHighlight,
  Dimensions,
} from 'react-native';
import {
  Table,
  TableWrapper,
  Row,
  Rows,
  Col,
  Cols,
  Cell,
} from 'react-native-table-component';
import FontAwesome from 'react-native-vector-icons/FontAwesome';
import {ActivityIndicator} from '@ant-design/react-native';
import DatePicker from 'react-native-datepicker';
import SelectDialog from 'react-native-select-dialog';
import {cwGet} from '../utils/http';
import banner from '../assets/sb.png';
import moment from 'moment';

export default class ReportPage extends Component {
  constructor(props) {
    super(props);
    this.state = {
      searchTime: moment().format('YYYY-MM-DD'),
      deviceList: [],
      animating: false,
      currentDevice: '',
      currentDeviceName: '',
      tableHead: [''],
      tableTitle: ['Title', 'Title2', 'Title3', 'Title4'],
      leftCol: [
        '0:00',
        '1:00',
        '2:00',
        '3:00',
        '4:00',
        '5:00',
        '6:00',
        '7:00',
        '8:00',
        '9:00',
        '10:00',
        '11:00',
        '12:00',
        '13:00',
        '14:00',
        '15:00',
        '16:00',
        '17:00',
        '18:00',
        '19:00',
        '20:00',
        '21:00',
        '22:00',
        '23:00',
        '平均值',
      ],
      // tableHead: ['时间', '中心流', '边缘流', '理论温度', '边缘指数', '蒸汽压力', '风口面积', '标准风速', '实际风速', '富氧率', '富氧量', '炉腹煤气指数', '煤气产生量', '煤气利用率', '左尺', '右尺', '冷风流量', '冷风压力', '热风压力', '热风温度', '透气性', '高炉压差', '顶压', '炉顶中心', '炉喉中心', '平均顶温', '瞬时喷煤', '前小时喷吹量', '00CO', 'CH4', 'CO2', 'H2'],
      // tableTitle: ['Title', 'Title2', 'Title3', 'Title4'],
      widthArr: [],
      tableData: [],
    };
  }
  componentDidMount() {
    this.setState(
      {
        currentDevice: global.nowDevice.id,
        currentDeviceName: global.nowDevice.name,
      },
      () => {
        this.getReportData(this);
      },
    );
  }
  onDeviceChange(item, index) {
    this.setState({
      currentDevice: item.id,
      currentDeviceName: item.name,
    });
  }

  getReportData() {
    const {currentDevice, searchTime} = this.state;
    console.log(currentDevice, searchTime);
    if (!currentDevice) {
      ToastAndroid.show('请先选择一个设备', ToastAndroid.SHORT);
    } else if (!searchTime) {
      ToastAndroid.show('请先选择一个时间', ToastAndroid.SHORT);
    } else {
      console.log(currentDevice, searchTime);
      this.setState({
        animating: true,
      });
      cwGet(
        'History/GetSummary?deviceID=' +
          currentDevice +
          '&date=' +
          encodeURIComponent(searchTime),
      ).then(res => {
        console.log('hahahahaha');
        console.log(res);
        var all = {};
        var tableHeader = ['时间'];
        var widthArr = [];
        var keys = [];
        var tableData = [];
        for (let item of res) {
          if (!all[item.name]) {
            tableHeader.push(item.name);
            widthArr.push(180);
            all[item.name] = [];
            all[item.name].push(item.value);
          } else {
            all[item.name].push(item.value);
          }
        }
        var allValues = Object.values(all);
        console.log(this.state.leftCol.length, 'length');
        for (let i = 0; i < this.state.leftCol.length; i++) {
          var a = [];
          a.push(this.state.leftCol[i]);
          for (let item of allValues) {
            a.push(item[i]);
          }
          tableData.push(a);
        }
        console.log(tableData);
        this.setState({
          tableHead: tableHeader,
          widthArr,
          tableData,
          animating: false,
        });
      });
    }
  }

  show() {
    this.refs.device.show();
  }

  defineList(rowData, rowID, highlighted) {
    return <Text style={{padding: 10}}>{rowData.name}</Text>;
  }

  render() {
    const state = this.state;
    const deviceWidth = Dimensions.get('window').width;
    // const tableData = [];
    // for (let i = 0; i < 30; i += 1) {
    //     const rowData = [];
    //     for (let j = 0; j < 9; j += 1) {
    //         rowData.push(`${i}${j}`);
    //     }
    //     tableData.push(rowData);
    // }
    // console.log(tableData)
    return (
      <View>
        <View
          style={{
            marginLeft: 20,
            flexDirection: 'row',
            marginTop: 5,
            marginBottom: 5,
            alignItems: 'center',
          }}>
          <FontAwesome
            style={{backgroundColor: 'transparent', marginRight: 20}}
            name="bars"
            color="grey"
            size={16}
          />
          <Text>报表</Text>
          <FontAwesome
            style={{
              backgroundColor: 'transparent',
              marginRight: 10,
              marginLeft: 10,
            }}
            name="chevron-left"
            color="grey"
            size={16}
          />
          <Text>{global.nowDevice.name}</Text>
          <FontAwesome
            style={{
              backgroundColor: 'transparent',
              marginRight: 10,
              marginLeft: 10,
            }}
            name="chevron-left"
            color="grey"
            size={16}
          />
          <Text>日</Text>
        </View>

        <View
          style={{flexDirection: 'row', alignItems: 'center', paddingLeft: 16}}>
          <Text>时间：</Text>
          <DatePicker
            style={{width: 100, marginRight: 10}}
            date={this.state.searchTime}
            mode="date"
            placeholder="选择日期"
            format="YYYY-MM-DD"
            showIcon={false}
            is24Hour={true}
            maxDate={moment()
              .subtract(1, 'days')
              .format('YYYY-MM-DD')}
            confirmBtnText="确定"
            cancelBtnText="取消"
            customStyles={{
              dateInput: {
                height: 30,
                borderColor: '#E2B0B0',
                borderRadius: 3,
                overflow: 'hidden',
              },
            }}
            onDateChange={date => {
              this.setState({searchTime: date});
            }}
          />
          <TouchableHighlight
            underlayColor="#"
            style={{
              height: 30,
              flexDirection: 'row',
              padding: 5,
              borderRadius: 3,
              alignItems: 'center',
              backgroundColor: '#E8B5E1',
            }}
            onPress={this.getReportData.bind(this)}
            underlayColor={'#transparent'}>
            <Text>查询</Text>
          </TouchableHighlight>
        </View>
        <View style={styles.container}>
          <ActivityIndicator
            animating={this.state.animating}
            toast
            size="large"
            text="加载中..."
          />
          <ScrollView
            horizontal={true}
            style={{height: Dimensions.get('window').height - 160}}>
            {state.tableData.length > 0 ? (
              <View>
                <Table borderStyle={{borderWidth: 1, borderColor: '#808080'}}>
                  <Row
                    data={state.tableHead}
                    widthArr={state.widthArr}
                    style={styles.header}
                    textStyle={styles.text}
                  />
                </Table>
                <ScrollView horizontal={false} style={styles.dataWrapper}>
                  <Table
                    borderStyle={{borderWidth: 0.5, borderColor: '#808080'}}>
                    {state.tableData.map((rowData, index) => (
                      <Row
                        key={index}
                        data={rowData}
                        widthArr={state.widthArr}
                        style={[
                          styles.row,
                          index % 2 == 0 && {backgroundColor: '#DDCCF7'},
                        ]}
                        textStyle={styles.text}
                      />
                    ))}
                  </Table>
                </ScrollView>
              </View>
            ) : (
              <></>
            )}
          </ScrollView>
        </View>
      </View>
    );
  }
}

const styles = StyleSheet.create({
  container: {
    backgroundColor: '#fff',
    paddingHorizontal: 5,
  },
  header: {
    height: 30,
    borderBottomWidth: 0,
    borderTopWidth: 1,
    backgroundColor: '#BBCCF7',
    borderBottomWidth: 1,
  },
  text: {textAlign: 'center', fontSize: 12},
  dataWrapper: {marginTop: -1},
  row: {height: 30, backgroundColor: '#DDEBF7'},
  wrapper: {flexDirection: 'row'},
});
